﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Text;
using LumiSoft.Net.MIME;
using LumiSoft.Net.Mail;
using LumiSoft.Net.SMTP.Client;
using Sharp.Framework.Logger;

namespace Sharp.Framework.Email
{
    public interface IEmailUnity
    { 
        /// <summary>
        /// 系统邮件立即发送
        /// </summary>
        /// <param name="command"></param>
        bool SystemMailSend(SystemMailCommand command);
    }

    [Serializable] 
    public class SystemMailCommand
    { 
        
        /// <summary>
        /// 收件人别名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 收件人邮件地址
        /// </summary>
        [Required]
        public string Email { get; set; } 

        /// <summary>
        /// 邮件主题
        /// </summary>
        [Required]
        public string Title { get; set; }

        /// <summary>
        /// 邮件内容
        /// </summary>
        [Required]
        public string Content { get; set; }
        /// <summary>
        /// 发件人
        /// </summary>
        [Required]
        public string Sender { get; set; }
        /// <summary>
        /// 发件人名称
        /// </summary>
        [Required]
        public string SenderName { get; set; }
        /// <summary>
        /// 发件账号密码
        /// </summary>
        [Required]
        public string Password { get; set; }
        /// <summary>
        /// smtp服务器
        /// </summary>
        [Required]
        public string Smtp { get; set; }
        /// <summary>
        /// 端口号
        /// </summary>
        [Required]
        public int Port { get; set; }
    }
    public class EmailUnity : IEmailUnity
    {
        /// <summary>
        /// 系统邮件立即发送
        /// </summary>
        /// <param name="command"></param>
        public bool SystemMailSend(SystemMailCommand command)
        {
            var smtpServer = command.Smtp;
            var smtpPort = command.Port;
            var sysMailName = command.SenderName;
            var sysMailAddr = command.Sender;
            var sysMailPwd = command.Password;

            try
            {
                var ms = new MemoryStream();
                var mailMessage = CreatePlainTextHtmlMessage(command.Email, command.Name,
                                                                         command.Title, command.Content,
                                                                         sysMailName, sysMailAddr);
                mailMessage.ToStream(ms, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8),
                                     Encoding.UTF8);
                ms.Position = 0;

                SMTP_Client.QuickSendSmartHost(null, smtpServer, smtpPort, false, sysMailAddr, sysMailPwd, sysMailAddr,
                                               new[] {command.Email}, ms);
#if DEBUG
                Log.Debug( 
                          string.Format("系统邮件发送成功, 接收人[{0}], 主题[{1}], 内容[{2}]", command.Email,
                                        command.Title, command.Content));

#endif
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(ex,
                          string.Format("系统邮件发送失败, 接收人[{0}], 主题[{1}], 内容[{2}]", command.Email,
                                        command.Title, command.Content));
                return false;
            }
        }

        private static Mail_Message CreatePlainTextHtmlMessage(string mailto, string mailtoName, string mailTitle, string mailContent, string mailFromName, string mailFromEmail)
        {
            var msg = new Mail_Message
            {
                MimeVersion = "1.0",
                MessageID = MIME_Utils.CreateMessageID(),
                Date = DateTime.Now,
                From = new Mail_t_MailboxList(),
                To = new Mail_t_AddressList(),
                Cc = new Mail_t_AddressList()
            };
            msg.From.Add(new Mail_t_Mailbox(mailFromName, mailFromEmail));

            msg.To.Add(new Mail_t_Mailbox(mailtoName, mailto));
        

            msg.Subject = mailTitle;

            #region MyRegion
            //--- multipart/mixed -----------------------------------
            var contentTypeOfMultipartMixed = new MIME_h_ContentType(MIME_MediaTypes.Multipart.mixed) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') };
            var multipartMixed = new MIME_b_MultipartMixed(contentTypeOfMultipartMixed);
            msg.Body = multipartMixed;

            //--- multipart/alternative -----------------------------
            var entityOfMultipartAlternative = new MIME_Entity();
            var contentTypeOfMultipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative) { Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.') };
            var multipartAlternative = new MIME_b_MultipartAlternative(contentTypeOfMultipartAlternative);
            entityOfMultipartAlternative.Body = multipartAlternative;
            multipartMixed.BodyParts.Add(entityOfMultipartAlternative);

            //--- text/plain ----------------------------------------
            var entityTextPlain = new MIME_Entity();
            var textPlain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
            entityTextPlain.Body = textPlain;

            //普通文本邮件内容，如果对方的收件客户端不支持HTML，这是必需的
            var plainTextBody = "如果你邮件客户端不支持HTML格式，或者你切换到“普通文本”视图，将看到此内容";
            //应作移除html标签操作
            if (!string.IsNullOrEmpty(mailContent))
            {
                plainTextBody = mailContent;
            }

            textPlain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, plainTextBody);
            multipartAlternative.BodyParts.Add(entityTextPlain);

            //--- text/html -----------------------------------------
            var htmlText = mailContent;
            var entityTextHtml = new MIME_Entity();
            var textHtml = new MIME_b_Text(MIME_MediaTypes.Text.html);
            entityTextHtml.Body = textHtml;
            textHtml.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, htmlText);
            multipartAlternative.BodyParts.Add(entityTextHtml);

            #endregion

            return msg;
        }
    }
}